import { Settings2, TestTube2, Volume2, Eye, EyeOff, Plus, X, Clock, Shuffle, MessageSquareText, Pause as PauseIcon, RefreshCw, MessageCircle } from 'lucide-react'
import { useState } from 'react'
import { Button } from '@/components/ui/button'
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
} from '@/components/ui/dialog'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select'
import { Separator } from '@/components/ui/separator'
import { Slider } from '@/components/ui/slider'
import { Switch } from '@/components/ui/switch'
import { useAIAssist } from '@/hooks/useAIAssist'
import { useAutoReply } from '@/hooks/useAutoReply'
import { useToast } from '@/hooks/useToast'
import { Badge } from '@/components/ui/badge'
import { IPC_CHANNELS } from 'shared/ipcChannels'
import { Textarea } from '@/components/ui/textarea'
import { ScrollArea } from '@/components/ui/scroll-area'
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'
import { Checkbox } from '@/components/ui/checkbox'
import { PRESET_VOICES, PRESET_VOICES_ALIYUN, PRESET_VOICES_TENCENT, PRESET_VOICES_EDGE } from 'shared/constants'

interface ConfigDialogProps {
  open: boolean
  onOpenChange: (open: boolean) => void
}

// 根据语音服务厂商获取对应的预设音色列表
const getPresetVoicesByProvider = (provider?: 'aliyun' | 'tencent' | 'edge') => {
  if (provider === 'edge') {
    return PRESET_VOICES_EDGE
  } else if (provider === 'tencent') {
    return PRESET_VOICES_TENCENT
  } else {
    return PRESET_VOICES_ALIYUN
  }
}

// 获取当前厂商的名称
const getProviderName = (provider?: 'aliyun' | 'tencent' | 'edge') => {
  if (provider === 'edge') return 'Edge-TTS'
  if (provider === 'tencent') return '腾讯云'
  return '阿里云'
}

export default function ConfigDialog({ open, onOpenChange }: ConfigDialogProps) {
  const { config, updateConfig, testVoiceConfig } = useAIAssist()
  const { config: autoReplyConfig, updateBlockList } = useAutoReply()
  const { toast } = useToast()
  const [testing, setTesting] = useState(false)
  const [previewing, setPreviewing] = useState(false)
  const [showAccessKeyId, setShowAccessKeyId] = useState(false)
  const [showAccessKeySecret, setShowAccessKeySecret] = useState(false)
  const [showAppKey, setShowAppKey] = useState(false)
  const [showTencentSecretId, setShowTencentSecretId] = useState(false)
  const [showTencentSecretKey, setShowTencentSecretKey] = useState(false)
  const [customTestText, setCustomTestText] = useState('')
  const [newVoiceId, setNewVoiceId] = useState('')
  const [newVoiceName, setNewVoiceName] = useState('')
  const [newBlockedUser, setNewBlockedUser] = useState('')

  // 确保 playback 配置存在，提供默认值
  const playbackConfig = {
    interval: config.playback?.interval ?? { min: 3, max: 10 },
    randomization: config.playback?.randomization ?? {
      enable: false,
      speedRange: [0.9, 1.1] as [number, number],
      volumeRange: [45, 55] as [number, number],
      pitchRange: [-50, 50] as [number, number],
    },
    recycle: config.playback?.recycle ?? {
      enable: false,
      probability: 20,
    },
    timeAnnouncement: config.playback?.timeAnnouncement ?? {
      enable: false,
      interval: { min: 5, max: 15 },
      templates: ['现在是{时间}', '当前时间{时间}'],
      mode: 'random' as 'random' | 'sequential',
    },
    userInteraction: config.playback?.userInteraction ?? {
      enable: false,
      interval: { min: 30, max: 60 },
      deduplication: { enable: true, duration: 60 },
      templates: {
        room_enter: ['欢迎{用户}来到直播间', '欢迎{用户}的到来', '{用户}来啦，大家欢迎'],
        room_like: ['感谢{用户}的点赞', '谢谢{用户}点赞支持', '{用户}点赞了，谢谢支持'],
        room_follow: ['感谢{用户}的关注', '欢迎{用户}关注直播间', '谢谢{用户}关注'],
        subscribe_merchant_brand_vip: ['欢迎{用户}加入品牌会员', '感谢{用户}成为品牌会员', '{用户}加入了品牌会员，感谢支持'],
        live_order: ['感谢{用户}购买{商品}', '谢谢{用户}的订单', '{用户}购买了{商品}，感谢支持'],
        ecom_fansclub_participate: ['欢迎{用户}加入粉丝团', '感谢{用户}加入粉丝团', '{用户}加入粉丝团啦，谢谢支持'],
      },
      mode: 'random' as 'random' | 'sequential',
      playMode: 'next' as 'immediate' | 'next', // ✅ 新增：默认等待播放完成
    },
    // 兼容旧版本配置
    welcomeUser: config.playback?.welcomeUser ?? {
      enable: false,
      interval: { min: 1, max: 5 },
      templates: ['欢迎{用户}来到直播间', '感谢{用户}的关注'],
      mode: 'random' as 'random' | 'sequential',
    },
    pause: config.playback?.pause ?? { enable: false, duration: [200, 500] as [number, number] },
  }

  const handleTestConfig = async () => {
    // 根据厂商验证配置
    if (!config.provider || config.provider === 'aliyun') {
      if (!config.aliyun.accessKeyId || !config.aliyun.accessKeySecret || !config.aliyun.appKey) {
        toast.error('请先配置阿里云 AccessKey ID、AccessKey Secret 和 Appkey')
        return
      }
    } else if (config.provider === 'tencent') {
      if (!config.tencent?.secretId || !config.tencent?.secretKey) {
        toast.error('请先配置腾讯云 SecretId 和 SecretKey')
        return
      }
    } else if (config.provider === 'edge') {
      // Edge-TTS 不需要验证配置，直接测试即可
      if (!config.edge?.voice) {
        toast.error('请先选择 Edge-TTS 语音音色')
        return
      }
    }

    setTesting(true)
    
    try {
      const result = await testVoiceConfig()
      if (result.success) {
        toast.success('配置测试成功！')
      } else {
        toast.error(`配置测试失败: ${result.error}`)
      }
    } catch (err) {
      toast.error('配置测试失败')
    } finally {
      setTesting(false)
    }
  }

  const handlePreviewVoice = async () => {
    // 根据厂商验证配置
    if (!config.provider || config.provider === 'aliyun') {
      if (!config.aliyun.accessKeyId || !config.aliyun.accessKeySecret || !config.aliyun.appKey) {
        toast.error('请先配置阿里云 AccessKey ID、AccessKey Secret 和 Appkey')
        return
      }
      // 检查是否选择了音色
      if (config.voice.type === 'preset' && !config.voice.presetVoiceId) {
        toast.error('请先选择一个预设音色')
        return
      }
      if (config.voice.type === 'clone' && !config.voice.cloneVoiceId) {
        toast.error('请先输入克隆音色 ID')
        return
      }
    } else if (config.provider === 'tencent') {
      if (!config.tencent?.secretId || !config.tencent?.secretKey) {
        toast.error('请先配置腾讯云 SecretId 和 SecretKey')
        return
      }
      // 检查是否选择了音色
      if (config.voice.type === 'preset' && !config.voice.presetVoiceId) {
        toast.error('请先选择一个预设音色')
        return
      }
      if (config.voice.type === 'clone' && !config.voice.cloneVoiceId) {
        toast.error('请先输入克隆音色 ID')
        return
      }
    } else if (config.provider === 'edge') {
      // Edge-TTS 不需要 API 密钥，只需要语音配置
      if (!config.edge?.voice) {
        toast.error('请先选择 Edge-TTS 语音音色')
        return
      }
    }

    setPreviewing(true)
    try {
      let testText: string
      
      if (config.provider === 'edge') {
        // Edge-TTS 的试听文本（只保留最自然的普通话音色）
        const edgeVoiceMap: Record<string, string> = {
          'zh-CN-XiaoxiaoNeural': '晓晓',
          'zh-CN-XiaoyiNeural': '晓伊',
          'zh-CN-YunxiNeural': '云希',
          'zh-CN-YunjianNeural': '云健',
          'zh-CN-YunyangNeural': '云扬',
        }
        const voiceName = edgeVoiceMap[config.edge?.voice || ''] || 'Edge-TTS'
        testText = customTestText.trim() || `您好，这是${voiceName}的试听效果，欢迎使用语音播报功能！`
      } else {
        // 阿里云/腾讯云/Edge-TTS 的试听文本
        const presetVoices = getPresetVoicesByProvider(config.provider)
        const allVoices = [...presetVoices, ...(config.voice.customVoices || [])]
        const voiceName =
          config.voice.type === 'preset'
            ? allVoices.find(v => v.id === config.voice.presetVoiceId)?.name
            : '您的克隆音色'
        testText = customTestText.trim() || `您好，这是${voiceName}的试听效果，欢迎使用语音播报功能！`
      }

      await window.ipcRenderer.invoke(
        IPC_CHANNELS.tasks.aiAssist.synthesizeVoice,
        {
          text: testText,
          voiceConfig: config,
        },
      )

      toast.success('试听成功！')
    } catch (err) {
      console.error('试听失败:', err)
      toast.error('试听失败，请检查配置')
    } finally {
      setPreviewing(false)
    }
  }

  const handleAddCustomVoice = () => {
    if (!newVoiceId.trim() || !newVoiceName.trim()) {
      toast.error('请输入音色 ID 和名称')
      return
    }

    const customVoices = config.voice.customVoices || []
    
    // 检查是否已存在
    if (customVoices.some(v => v.id === newVoiceId.trim())) {
      toast.error('该音色 ID 已存在')
      return
    }

    // 根据厂商检查是否与预设音色冲突
    const presetVoices = getPresetVoicesByProvider(config.provider)
    if (presetVoices.some(v => v.id === newVoiceId.trim())) {
      toast.error('该音色 ID 与预设音色冲突')
      return
    }

    updateConfig({
      voice: {
        ...config.voice,
        customVoices: [
          ...customVoices,
          { id: newVoiceId.trim(), name: newVoiceName.trim() }
        ]
      }
    })

    setNewVoiceId('')
    setNewVoiceName('')
    toast.success('自定义音色添加成功')
  }

  const handleRemoveCustomVoice = (voiceId: string) => {
    const customVoices = config.voice.customVoices || []
    updateConfig({
      voice: {
        ...config.voice,
        customVoices: customVoices.filter(v => v.id !== voiceId)
      }
    })
    toast.success('已删除自定义音色')
  }

  // 用户屏蔽列表处理函数
  const handleAddBlockedUser = () => {
    if (!newBlockedUser.trim()) {
      toast.error('请输入用户名')
      return
    }
    
    if (autoReplyConfig.blockList.includes(newBlockedUser.trim())) {
      toast.error('该用户已在屏蔽列表中')
      return
    }

    updateBlockList([...autoReplyConfig.blockList, newBlockedUser.trim()])
    setNewBlockedUser('')
    toast.success('已添加到屏蔽列表')
  }

  const handleRemoveBlockedUser = (index: number) => {
    const updatedList = autoReplyConfig.blockList.filter((_, i) => i !== index)
    updateBlockList(updatedList)
    toast.success('已从屏蔽列表移除')
  }

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="max-w-3xl max-h-[90vh]">
        <DialogHeader>
          <DialogTitle className="flex items-center gap-2">
            <Settings2 className="h-5 w-5" />
            全局设置
          </DialogTitle>
          <DialogDescription>
            配置语音合成服务、语音播报参数和播放配置
          </DialogDescription>
        </DialogHeader>

        <Tabs defaultValue="voice" className="mt-4">
          <TabsList className="grid w-full grid-cols-3">
            <TabsTrigger value="voice">
              <Volume2 className="h-4 w-4 mr-2" />
              语音配置
            </TabsTrigger>
            <TabsTrigger value="playback">
              <Clock className="h-4 w-4 mr-2" />
              播放配置
            </TabsTrigger>
            <TabsTrigger value="comment">
              <MessageCircle className="h-4 w-4 mr-2" />
              用户评论配置
            </TabsTrigger>
          </TabsList>

          <ScrollArea className="max-h-[calc(90vh-200px)] mt-4">
            {/* 阿里云语音配置选项卡 */}
            <TabsContent value="voice" className="space-y-6 pr-4">
            {/* 厂商选择 */}
            <div className="space-y-3">
              <h4 className="text-sm font-medium">语音服务厂商</h4>
              <Select
                value={config.provider || 'aliyun'}
                onValueChange={(value: 'aliyun' | 'tencent' | 'edge') => {
                  // 切换厂商时，清理音色轮换中无效的音色ID
                  const presetVoices = getPresetVoicesByProvider(value)
                  const customVoices = config.voice.customVoices || []
                  const allValidVoiceIds = [...presetVoices, ...customVoices].map(v => v.id)
                  const currentVoiceIds = config.voice.voiceRotation?.voiceIds ?? []
                  const filteredVoiceIds = currentVoiceIds.filter(id => allValidVoiceIds.includes(id))
                  
                  updateConfig({ 
                    provider: value,
                    voice: {
                      ...config.voice,
                      voiceRotation: {
                        ...config.voice.voiceRotation!,
                        voiceIds: filteredVoiceIds,
                      },
                    },
                  })
                }}
              >
                <SelectTrigger>
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="aliyun">阿里云 CosyVoice</SelectItem>
                  <SelectItem value="tencent">腾讯云 TTS</SelectItem>
                  <SelectItem value="edge">Edge-TTS (免费)</SelectItem>
                </SelectContent>
              </Select>
              <p className="text-xs text-muted-foreground">
                选择您要使用的语音合成服务厂商
              </p>
            </div>

            <Separator />

            {/* 阿里云配置 */}
            {(!config.provider || config.provider === 'aliyun') && (
            <div className="space-y-4">
              <div className="flex items-center justify-between">
                <h4 className="text-sm font-medium">阿里云配置</h4>
                <Button
                  variant="outline"
                  size="sm"
                  onClick={handleTestConfig}
                  disabled={testing}
                >
                  <TestTube2 className="h-4 w-4 mr-1" />
                  {testing ? '测试中...' : '测试配置'}
                </Button>
              </div>
              <div className="space-y-3">
                <div className="space-y-2">
                  <Label htmlFor="accessKeyId">AccessKey ID</Label>
                  <div className="relative">
                    <Input
                      id="accessKeyId"
                      type={showAccessKeyId ? 'text' : 'password'}
                      placeholder="请输入阿里云 AccessKey ID"
                      value={config.aliyun.accessKeyId}
                      onChange={e =>
                        updateConfig({
                          aliyun: { ...config.aliyun, accessKeyId: e.target.value },
                        })
                      }
                      className="pr-10"
                    />
                    <Button
                      type="button"
                      variant="ghost"
                      size="sm"
                      className="absolute right-0 top-0 h-full px-3 py-2 hover:bg-transparent"
                      onClick={() => setShowAccessKeyId(!showAccessKeyId)}
                    >
                      {showAccessKeyId ? (
                        <EyeOff className="h-4 w-4 text-muted-foreground" />
                      ) : (
                        <Eye className="h-4 w-4 text-muted-foreground" />
                      )}
                    </Button>
                  </div>
                </div>
                <div className="space-y-2">
                  <Label htmlFor="accessKeySecret">AccessKey Secret</Label>
                  <div className="relative">
                    <Input
                      id="accessKeySecret"
                      type={showAccessKeySecret ? 'text' : 'password'}
                      placeholder="请输入阿里云 AccessKey Secret"
                      value={config.aliyun.accessKeySecret}
                      onChange={e =>
                        updateConfig({
                          aliyun: { ...config.aliyun, accessKeySecret: e.target.value },
                        })
                      }
                      className="pr-10"
                    />
                    <Button
                      type="button"
                      variant="ghost"
                      size="sm"
                      className="absolute right-0 top-0 h-full px-3 py-2 hover:bg-transparent"
                      onClick={() => setShowAccessKeySecret(!showAccessKeySecret)}
                    >
                      {showAccessKeySecret ? (
                        <EyeOff className="h-4 w-4 text-muted-foreground" />
                      ) : (
                        <Eye className="h-4 w-4 text-muted-foreground" />
                      )}
                    </Button>
                  </div>
                </div>
                <div className="space-y-2">
                  <Label htmlFor="appKey">Appkey (语音服务)</Label>
                  <div className="relative">
                    <Input
                      id="appKey"
                      type={showAppKey ? 'text' : 'password'}
                      placeholder="请输入智能语音交互应用的 Appkey"
                      value={config.aliyun.appKey}
                      onChange={e =>
                        updateConfig({
                          aliyun: { ...config.aliyun, appKey: e.target.value },
                        })
                      }
                      className="pr-10"
                    />
                    <Button
                      type="button"
                      variant="ghost"
                      size="sm"
                      className="absolute right-0 top-0 h-full px-3 py-2 hover:bg-transparent"
                      onClick={() => setShowAppKey(!showAppKey)}
                    >
                      {showAppKey ? (
                        <EyeOff className="h-4 w-4 text-muted-foreground" />
                      ) : (
                        <Eye className="h-4 w-4 text-muted-foreground" />
                      )}
                    </Button>
                  </div>
                  <p className="text-xs text-muted-foreground">
                    在智能语音交互控制台创建项目后获得
                  </p>
                </div>
                <div className="space-y-2">
                  <Label htmlFor="endpoint">Endpoint (可选)</Label>
                  <Input
                    id="endpoint"
                    placeholder="https://nls-gateway.aliyuncs.com/stream/v1/tts"
                    value={config.aliyun.endpoint || ''}
                    onChange={e =>
                      updateConfig({
                        aliyun: { ...config.aliyun, endpoint: e.target.value },
                      })
                    }
                  />
                  <p className="text-xs text-muted-foreground">
                    默认使用阿里云公共 endpoint，一般无需修改
                  </p>
                </div>
              </div>
            </div>
            )}

            {/* 腾讯云配置 */}
            {config.provider === 'tencent' && (
            <div className="space-y-4">
              <div className="flex items-center justify-between">
                <h4 className="text-sm font-medium">腾讯云配置</h4>
                <Button
                  variant="outline"
                  size="sm"
                  onClick={handleTestConfig}
                  disabled={testing}
                >
                  <TestTube2 className="h-4 w-4 mr-1" />
                  {testing ? '测试中...' : '测试配置'}
                </Button>
              </div>
              <div className="space-y-3">
                <div className="space-y-2">
                  <Label htmlFor="tencentSecretId">SecretId</Label>
                  <div className="relative">
                    <Input
                      id="tencentSecretId"
                      type={showTencentSecretId ? 'text' : 'password'}
                      placeholder="请输入腾讯云 SecretId"
                      value={config.tencent?.secretId || ''}
                      onChange={e =>
                        updateConfig({
                          tencent: { ...config.tencent, secretId: e.target.value },
                        })
                      }
                      className="pr-10"
                    />
                    <Button
                      type="button"
                      variant="ghost"
                      size="sm"
                      className="absolute right-0 top-0 h-full px-3 py-2 hover:bg-transparent"
                      onClick={() => setShowTencentSecretId(!showTencentSecretId)}
                    >
                      {showTencentSecretId ? (
                        <EyeOff className="h-4 w-4 text-muted-foreground" />
                      ) : (
                        <Eye className="h-4 w-4 text-muted-foreground" />
                      )}
                    </Button>
                  </div>
                </div>
                <div className="space-y-2">
                  <Label htmlFor="tencentSecretKey">SecretKey</Label>
                  <div className="relative">
                    <Input
                      id="tencentSecretKey"
                      type={showTencentSecretKey ? 'text' : 'password'}
                      placeholder="请输入腾讯云 SecretKey"
                      value={config.tencent?.secretKey || ''}
                      onChange={e =>
                        updateConfig({
                          tencent: { ...config.tencent, secretKey: e.target.value },
                        })
                      }
                      className="pr-10"
                    />
                    <Button
                      type="button"
                      variant="ghost"
                      size="sm"
                      className="absolute right-0 top-0 h-full px-3 py-2 hover:bg-transparent"
                      onClick={() => setShowTencentSecretKey(!showTencentSecretKey)}
                    >
                      {showTencentSecretKey ? (
                        <EyeOff className="h-4 w-4 text-muted-foreground" />
                      ) : (
                        <Eye className="h-4 w-4 text-muted-foreground" />
                      )}
                    </Button>
                  </div>
                  <p className="text-xs text-muted-foreground">
                    在腾讯云控制台获取：SecretId 和 SecretKey
                  </p>
                </div>
              </div>
            </div>
            )}

            {/* Edge-TTS 配置 */}
            {config.provider === 'edge' && (
            <div className="space-y-4">
              <div className="flex items-center justify-between">
                <h4 className="text-sm font-medium">Edge-TTS 配置</h4>
                <Button
                  variant="outline"
                  size="sm"
                  onClick={handleTestConfig}
                  disabled={testing}
                >
                  <TestTube2 className="h-4 w-4 mr-1" />
                  {testing ? '测试中...' : '测试配置'}
                </Button>
              </div>
              <div className="space-y-3">
                {/* 本地服务地址 */}
                <div className="space-y-2">
                  <Label htmlFor="edgeApiUrl">本地服务地址</Label>
                  <Input
                    id="edgeApiUrl"
                    placeholder="http://localhost:5000"
                    value={config.edge?.apiUrl || 'http://localhost:5000'}
                    onChange={e =>
                      updateConfig({
                        edge: { ...config.edge, apiUrl: e.target.value },
                      })
                    }
                  />
                  <p className="text-xs text-muted-foreground">
                    本地 Edge-TTS HTTP 服务的地址。点击"测试配置"时，如果服务未运行会自动启动。
                  </p>
                </div>

                <div className="space-y-2">
                  <div className="flex items-center justify-between">
                    <Label htmlFor="edgeVoice">语音音色</Label>
                    <Button
                      variant="outline"
                      size="sm"
                      onClick={handlePreviewVoice}
                      disabled={previewing}
                    >
                      <Volume2 className="h-4 w-4 mr-1" />
                      {previewing ? '试听中...' : '试听音色'}
                    </Button>
                  </div>
                  <Select
                    value={config.edge?.voice || 'zh-CN-XiaoxiaoNeural'}
                    onValueChange={value =>
                      updateConfig({
                        edge: { ...config.edge, voice: value },
                      })
                    }
                  >
                    <SelectTrigger>
                      <SelectValue />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="zh-CN-XiaoxiaoNeural">晓晓 (女声·自然)</SelectItem>
                      <SelectItem value="zh-CN-XiaoyiNeural">晓伊 (女声·温柔)</SelectItem>
                      <SelectItem value="zh-CN-YunxiNeural">云希 (男声·自然)</SelectItem>
                      <SelectItem value="zh-CN-YunjianNeural">云健 (男声·稳重)</SelectItem>
                      <SelectItem value="zh-CN-YunyangNeural">云扬 (男声·专业)</SelectItem>
                    </SelectContent>
                  </Select>
                  <p className="text-xs text-muted-foreground">
                    精选最自然的中文普通话音色，Edge-TTS 完全免费，由微软提供。
                  </p>
                </div>

                {/* 自定义试听文本 */}
                <div className="space-y-2">
                  <Label htmlFor="customTestText">
                    自定义试听文本 (选填)
                  </Label>
                  <Textarea
                    id="customTestText"
                    placeholder="输入您想要测试的文本内容，留空将使用默认文本..."
                    value={customTestText}
                    onChange={e => {
                      const text = e.target.value
                      if (text.length <= 150) {
                        setCustomTestText(text)
                      }
                    }}
                    className="min-h-[140px] resize-y"
                    maxLength={150}
                  />
                  <div className="flex justify-between items-center">
                    <p className="text-xs text-muted-foreground">
                      输入自定义文本来试听音色效果
                    </p>
                    <span className="text-xs text-muted-foreground">
                      {customTestText.length}/150
                    </span>
                  </div>
                </div>
              </div>
            </div>
            )}

            <Separator />

            {/* 音色选择 - Edge-TTS 使用自己的音色选择器，不显示此通用配置 */}
            {config.provider !== 'edge' && (
            <div className="space-y-3">
              <div className="flex items-center justify-between">
                <h4 className="text-sm font-medium">音色选择</h4>
                <Button
                  variant="outline"
                  size="sm"
                  onClick={handlePreviewVoice}
                  disabled={previewing}
                >
                  <Volume2 className="h-4 w-4 mr-1" />
                  {previewing ? '试听中...' : '试听音色'}
                </Button>
              </div>
              <div className="space-y-3">
                <div className="flex items-center gap-4">
                  <Label>音色类型</Label>
                  <div className="flex gap-2">
                    <Badge
                      variant={
                        config.voice.type === 'preset' ? 'default' : 'outline'
                      }
                      className="cursor-pointer"
                      onClick={() =>
                        updateConfig({ voice: { ...config.voice, type: 'preset' } })
                      }
                    >
                      预设音色
                    </Badge>
                    <Badge
                      variant={
                        config.voice.type === 'clone' ? 'default' : 'outline'
                      }
                      className="cursor-pointer"
                      onClick={() =>
                        updateConfig({ voice: { ...config.voice, type: 'clone' } })
                      }
                    >
                      克隆音色
                    </Badge>
                  </div>
                </div>

                {config.voice.type === 'preset' ? (
                  <div className="space-y-3">
                    <div className="space-y-2">
                      <Label htmlFor="presetVoice">选择音色</Label>
                      <Select
                        value={config.voice.presetVoiceId || ''}
                        onValueChange={value =>
                          updateConfig({
                            voice: { ...config.voice, presetVoiceId: value },
                          })
                        }
                      >
                        <SelectTrigger>
                          <SelectValue placeholder="选择音色" />
                        </SelectTrigger>
                        <SelectContent>
                          {/* 预设音色 */}
                          {(() => {
                            const presetVoices = getPresetVoicesByProvider(config.provider)
                            return presetVoices.length > 0 && (
                              <>
                                <div className="px-2 py-1.5 text-xs font-semibold text-muted-foreground">
                                  预设音色
                                </div>
                                {presetVoices.map(voice => (
                                  <SelectItem key={voice.id} value={voice.id}>
                                    {voice.name}
                                  </SelectItem>
                                ))}
                              </>
                            )
                          })()}
                          {/* 自定义音色 */}
                          {(config.voice.customVoices || []).length > 0 && (
                            <>
                              <div className="px-2 py-1.5 text-xs font-semibold text-muted-foreground border-t mt-1 pt-2">
                                自定义音色
                              </div>
                              {(config.voice.customVoices || []).map(voice => (
                                <SelectItem key={voice.id} value={voice.id}>
                                  {voice.name}
                                </SelectItem>
                              ))}
                            </>
                          )}
                        </SelectContent>
                      </Select>
                    </div>

                    {/* 添加自定义音色 */}
                    <div className="space-y-2 p-3 border rounded-md bg-muted/30">
                      <div className="flex items-center gap-2">
                        <Plus className="h-4 w-4" />
                        <Label className="text-sm font-medium">添加自定义音色</Label>
                      </div>
                      <div className="grid grid-cols-2 gap-2">
                        <Input
                          placeholder="音色 ID"
                          value={newVoiceId}
                          onChange={e => setNewVoiceId(e.target.value)}
                          onKeyDown={e => e.key === 'Enter' && handleAddCustomVoice()}
                        />
                        <Input
                          placeholder="音色名称"
                          value={newVoiceName}
                          onChange={e => setNewVoiceName(e.target.value)}
                          onKeyDown={e => e.key === 'Enter' && handleAddCustomVoice()}
                        />
                      </div>
                      <Button
                        size="sm"
                        variant="secondary"
                        className="w-full"
                        onClick={handleAddCustomVoice}
                      >
                        <Plus className="h-3 w-3 mr-1" />
                        添加
                      </Button>
                      <p className="text-xs text-muted-foreground">
                        输入{getProviderName(config.provider)}音色 ID 和自定义名称，例如克隆的音色
                      </p>
                    </div>

                    {/* 已添加的自定义音色列表 */}
                    {(config.voice.customVoices || []).length > 0 && (
                      <div className="space-y-2">
                        <Label className="text-sm">已添加的自定义音色</Label>
                        <div className="space-y-1 max-h-32 overflow-y-auto">
                          {(config.voice.customVoices || []).map(voice => (
                            <div
                              key={voice.id}
                              className="flex items-center justify-between p-2 border rounded-md bg-background hover:bg-accent/50 transition-colors"
                            >
                              <div className="flex flex-col">
                                <span className="text-sm font-medium">{voice.name}</span>
                                <span className="text-xs text-muted-foreground">ID: {voice.id}</span>
                              </div>
                              <Button
                                size="sm"
                                variant="ghost"
                                onClick={() => handleRemoveCustomVoice(voice.id)}
                                className="h-7 w-7 p-0 text-destructive hover:text-destructive"
                              >
                                <X className="h-4 w-4" />
                              </Button>
                            </div>
                          ))}
                        </div>
                      </div>
                    )}
                  </div>
                ) : (
                  <div className="space-y-2">
                    <Label htmlFor="cloneVoice">克隆音色 ID</Label>
                    <Input
                      id="cloneVoice"
                      placeholder="请输入您克隆的音色 ID"
                      value={config.voice.cloneVoiceId || ''}
                      onChange={e =>
                        updateConfig({
                          voice: { ...config.voice, cloneVoiceId: e.target.value },
                        })
                      }
                    />
                    <p className="text-xs text-muted-foreground">
                      您需要先在{(!config.provider || config.provider === 'aliyun') ? '阿里云' : '腾讯云'}控制台克隆声音，然后在此输入音色 ID
                    </p>
                  </div>
                )}

                {/* 自定义试听文本 */}
                <div className="space-y-2">
                  <Label htmlFor="customTestText">
                    自定义试听文本 (选填)
                  </Label>
                  <Textarea
                    id="customTestText"
                    placeholder="输入您想要测试的文本内容，留空将使用默认文本..."
                    value={customTestText}
                    onChange={e => {
                      const text = e.target.value
                      if (text.length <= 150) {
                        setCustomTestText(text)
                      }
                    }}
                    className="min-h-[140px] resize-y"
                    maxLength={150}
                  />
                  <div className="flex justify-between items-center">
                    <p className="text-xs text-muted-foreground">
                      输入自定义文本来试听音色效果
                    </p>
                    <span className="text-xs text-muted-foreground">
                      {customTestText.length}/150
                    </span>
                  </div>
                </div>
              </div>
            </div>
            )}

            <Separator />

            {/* 播报参数 */}
            <div className="space-y-4">
              <div className="flex items-center justify-between">
                <h4 className="text-sm font-medium">播报参数</h4>
                <div className="flex items-center gap-2">
                  <Switch
                    checked={config.broadcast.enable}
                    onCheckedChange={checked =>
                      updateConfig({
                        broadcast: { ...config.broadcast, enable: checked },
                      })
                    }
                  />
                  <Label>启用播报</Label>
                </div>
              </div>

              <div className="space-y-4">
                <div className="space-y-2">
                  <div className="flex justify-between">
                    <Label>语速</Label>
                    <span className="text-sm text-muted-foreground">
                      {config.broadcast.speed}x
                    </span>
                  </div>
                  <Slider
                    value={[config.broadcast.speed]}
                    onValueChange={([value]) =>
                      updateConfig({
                        broadcast: { ...config.broadcast, speed: value },
                      })
                    }
                    min={0.5}
                    max={2.0}
                    step={0.1}
                    disabled={!config.broadcast.enable}
                  />
                </div>

                <div className="space-y-2">
                  <div className="flex justify-between">
                    <Label>音量</Label>
                    <span className="text-sm text-muted-foreground">
                      {config.broadcast.volume}
                    </span>
                  </div>
                  <Slider
                    value={[config.broadcast.volume]}
                    onValueChange={([value]) =>
                      updateConfig({
                        broadcast: { ...config.broadcast, volume: value },
                      })
                    }
                    min={0}
                    max={100}
                    step={1}
                    disabled={!config.broadcast.enable}
                  />
                </div>

                <div className="space-y-2">
                  <div className="flex justify-between">
                    <Label>音调</Label>
                    <span className="text-sm text-muted-foreground">
                      {config.broadcast.pitch}
                    </span>
                  </div>
                  <Slider
                    value={[config.broadcast.pitch]}
                    onValueChange={([value]) =>
                      updateConfig({
                        broadcast: { ...config.broadcast, pitch: value },
                      })
                    }
                    min={-500}
                    max={500}
                    step={10}
                    disabled={!config.broadcast.enable}
                  />
                </div>
              </div>
            </div>
            </TabsContent>

            {/* 用户评论配置选项卡 */}
            <TabsContent value="comment" className="space-y-6 pr-4">
              {/* 评论过滤 */}
              <div className="space-y-3">
                <div className="flex items-center justify-between">
                  <h4 className="text-sm font-medium">评论过滤</h4>
                  <div className="flex items-center gap-2">
                    <Switch
                      checked={config.commentFilter.enableFilter}
                      onCheckedChange={checked =>
                        updateConfig({
                          commentFilter: {
                            ...config.commentFilter,
                            enableFilter: checked,
                          },
                        })
                      }
                    />
                    <Label>启用过滤</Label>
                  </div>
                </div>
                {config.commentFilter.enableFilter && (
                  <div className="space-y-2">
                    <Label htmlFor="keywords">关键词 (每行一个)</Label>
                    <Textarea
                      id="keywords"
                      placeholder="例如:&#10;产品&#10;价格&#10;优惠"
                      value={config.commentFilter.keywords.join('\n')}
                      onChange={e =>
                        updateConfig({
                          commentFilter: {
                            ...config.commentFilter,
                            keywords: e.target.value.split('\n'),
                          },
                        })
                      }
                      onBlur={e =>
                        updateConfig({
                          commentFilter: {
                            ...config.commentFilter,
                            keywords: e.target.value
                              .split('\n')
                              .map(k => k.trim())
                              .filter(Boolean),
                          },
                        })
                      }
                      className="min-h-[140px] resize-y"
                    />
                    <p className="text-xs text-muted-foreground">
                      只播报包含这些关键词的评论，每行输入一个关键词
                    </p>
                    <p className="text-xs text-blue-600 dark:text-blue-400">
                      💡 监听来源（中控台/大屏）在"自动回复"页面配置
                    </p>
                  </div>
                )}
              </div>

              <Separator />

              {/* AI智能回复 */}
              <div className="space-y-4">
                <div className="flex items-center justify-between">
                  <div>
                    <h4 className="text-sm font-medium">AI智能回复</h4>
                    <p className="text-xs text-muted-foreground mt-1">
                      根据关键词自动检测评论并使用AI生成语音回复
                    </p>
                  </div>
                  <div className="flex items-center gap-2">
                    <Switch
                      checked={config.smartReply?.enable ?? false}
                      onCheckedChange={checked =>
                        updateConfig({
                          smartReply: {
                            ...(config.smartReply || {
                              checkInterval: 5,
                              keywords: [],
                              deduplication: {
                                userInterval: 120,
                                questionInterval: 3600,
                              },
                            }),
                            enable: checked,
                          },
                        })
                      }
                    />
                    <Label>启用</Label>
                  </div>
                </div>

                {config.smartReply?.enable && (
                  <div className="space-y-4 pl-6">
                    {/* 检测间隔 */}
                    <div className="space-y-2">
                      <Label htmlFor="checkInterval">检测间隔 (秒)</Label>
                      <Input
                        id="checkInterval"
                        type="number"
                        min={3}
                        max={60}
                        value={config.smartReply?.checkInterval ?? 5}
                        onChange={e =>
                          updateConfig({
                            smartReply: {
                              ...config.smartReply!,
                              checkInterval: Number(e.target.value),
                            },
                          })
                        }
                      />
                      <p className="text-xs text-muted-foreground">
                        多少秒检查一次评论列表，匹配到关键词后触发AI回复
                      </p>
                    </div>

                    {/* 触发关键词 */}
                    <div className="space-y-2">
                      <Label htmlFor="smartReplyKeywords">触发关键词 (每行一个)</Label>
                      <Textarea
                        id="smartReplyKeywords"
                        placeholder="例如:&#10;多少钱&#10;价格&#10;怎么买&#10;在哪买"
                        value={(config.smartReply?.keywords || []).join('\n')}
                        onChange={e =>
                          updateConfig({
                            smartReply: {
                              ...config.smartReply!,
                              keywords: e.target.value.split('\n'),
                            },
                          })
                        }
                        onBlur={e =>
                          updateConfig({
                            smartReply: {
                              ...config.smartReply!,
                              keywords: e.target.value
                                .split('\n')
                                .map(k => k.trim())
                                .filter(Boolean),
                            },
                          })
                        }
                        className="min-h-[160px] resize-y"
                      />
                      <p className="text-xs text-muted-foreground">
                        💡 评论包含这些关键词时，会触发AI智能语音回复（智能模糊匹配：自动忽略语气词和标点符号，如"录播吧"可以匹配"这是录播吗"）
                      </p>
                    </div>

                    {/* 播放模式配置 */}
                    <div className="space-y-2 border-t pt-3">
                      <Label htmlFor="smartReplyPlayMode">播放模式</Label>
                      <Select
                        value={config.smartReply?.playMode || 'next'}
                        onValueChange={(value: 'immediate' | 'next') =>
                          updateConfig({
                            smartReply: {
                              ...config.smartReply!,
                              playMode: value,
                            },
                          })
                        }
                      >
                        <SelectTrigger id="smartReplyPlayMode">
                          <SelectValue />
                        </SelectTrigger>
                        <SelectContent>
                          <SelectItem value="immediate">立即播放（打断当前）</SelectItem>
                          <SelectItem value="next">等待播放完成</SelectItem>
                        </SelectContent>
                      </Select>
                      <p className="text-xs text-muted-foreground">
                        选择AI智能回复的播放方式：立即打断当前播放，还是等待当前播放完成后再播放
                      </p>
                    </div>

                    {/* 防重复配置 */}
                    <div className="space-y-3 border-t pt-3">
                      <Label className="text-sm font-medium">防重复回复</Label>
                      
                      <div className="space-y-2">
                        <Label htmlFor="userInterval">同一用户回复间隔 (秒)</Label>
                        <Input
                          id="userInterval"
                          type="number"
                          min={30}
                          max={600}
                          value={config.smartReply?.deduplication?.userInterval ?? 120}
                          onChange={e =>
                            updateConfig({
                              smartReply: {
                                ...config.smartReply!,
                                deduplication: {
                                  ...config.smartReply!.deduplication,
                                  userInterval: Number(e.target.value),
                                },
                              },
                            })
                          }
                        />
                        <p className="text-xs text-muted-foreground">
                          在此时间内，不重复回复同一用户的任何问题
                        </p>
                      </div>

                      <div className="space-y-2">
                        <Label htmlFor="questionInterval">同一问题回复间隔 (秒)</Label>
                        <Input
                          id="questionInterval"
                          type="number"
                          min={0}
                          max={86400}
                          value={config.smartReply?.deduplication?.questionInterval ?? 3600}
                          onChange={e =>
                            updateConfig({
                              smartReply: {
                                ...config.smartReply!,
                                deduplication: {
                                  ...config.smartReply!.deduplication,
                                  questionInterval: Number(e.target.value),
                                },
                              },
                            })
                          }
                        />
                        <p className="text-xs text-muted-foreground">
                          同一用户问同一个问题（如"多少钱"）的回复间隔，0表示不限制
                        </p>
                      </div>
                    </div>

                    {/* 提示信息 */}
                    <div className="bg-blue-50 dark:bg-blue-950 p-3 rounded-md text-xs space-y-1">
                      <p className="font-medium">💡 使用说明：</p>
                      <ul className="list-disc list-inside space-y-1 text-muted-foreground">
                        <li>需要先启动评论监听，智能回复才会生效</li>
                        <li>监听来源在"自动回复"页面配置（中控台/大屏）</li>
                        <li>检测到关键词后，AI生成回复内容并使用TTS语音播报</li>
                        <li>回复时会带上用户昵称，例如"小明，这个产品只要99元"</li>
                        <li>AI会根据"AI助手"页面的直播配置参数生成回复</li>
                        <li>需要配置阿里云TTS参数才能语音播报</li>
                        <li>建议配置产品信息、角色定位等参数，让回复更准确</li>
                        <li>防重复机制避免对同一用户频繁回复，提升直播间体验</li>
                        <li>
                          <strong>播放模式</strong>：
                          {config.smartReply?.playMode === 'immediate' 
                            ? '立即播放（会打断当前播放）' 
                            : '等待播放完成（不会打断，排队播放）'}
                        </li>
                      </ul>
                    </div>
                  </div>
                )}
              </div>

              <Separator />

              {/* 用户屏蔽列表 */}
              <div className="space-y-3">
                <div>
                  <h4 className="text-sm font-medium">用户屏蔽列表</h4>
                  <p className="text-sm text-muted-foreground">
                    屏蔽列表中的用户将不会被自动回复
                  </p>
                </div>

                <div className="space-y-2 max-h-[200px] overflow-y-auto border rounded-md p-2">
                  {autoReplyConfig.blockList.length === 0 ? (
                    <div className="text-sm text-center py-4 text-muted-foreground">
                      暂无屏蔽用户
                    </div>
                  ) : (
                    autoReplyConfig.blockList.map((user, index) => (
                      // biome-ignore lint/suspicious/noArrayIndexKey: 下标无妨
                      <div key={index} className="flex items-center gap-2 group">
                        <div className="flex-1 text-sm p-2 rounded bg-muted/50">
                          {user}
                        </div>
                        <Button
                          variant="ghost"
                          size="icon"
                          className="h-8 w-8 opacity-0 group-hover:opacity-100 transition-opacity"
                          onClick={() => handleRemoveBlockedUser(index)}
                        >
                          <X className="h-4 w-4" />
                        </Button>
                      </div>
                    ))
                  )}
                </div>

                <div className="flex items-center gap-2">
                  <Input
                    placeholder="输入用户名..."
                    value={newBlockedUser}
                    onChange={e => setNewBlockedUser(e.target.value)}
                    onKeyDown={e => e.key === 'Enter' && handleAddBlockedUser()}
                    className="flex-1"
                  />
                  <Button onClick={handleAddBlockedUser}>添加</Button>
                </div>
              </div>
            </TabsContent>

            {/* 播放配置选项卡 */}
            <TabsContent value="playback" className="space-y-6 pr-4">
              {/* 播放间隔配置 */}
              <div className="space-y-4">
                <div className="flex items-center gap-2">
                  <Clock className="h-4 w-4 text-muted-foreground" />
                  <h4 className="text-sm font-medium">播放间隔</h4>
                </div>
                <div className="space-y-3 pl-6">
                  <div className="grid grid-cols-2 gap-3">
                    <div className="space-y-2">
                      <Label htmlFor="intervalMin">最小间隔 (秒)</Label>
                      <Input
                        id="intervalMin"
                        type="number"
                        min={1}
                        max={60}
                        value={playbackConfig.interval.min}
                        onChange={e =>
                          updateConfig({
                            playback: {
                              ...playbackConfig,
                              interval: {
                                ...playbackConfig.interval,
                                min: Number(e.target.value),
                              },
                            },
                          })
                        }
                      />
                    </div>
                    <div className="space-y-2">
                      <Label htmlFor="intervalMax">最大间隔 (秒)</Label>
                      <Input
                        id="intervalMax"
                        type="number"
                        min={1}
                        max={60}
                        value={playbackConfig.interval.max}
                        onChange={e =>
                          updateConfig({
                            playback: {
                              ...playbackConfig,
                              interval: {
                                ...playbackConfig.interval,
                                max: Number(e.target.value),
                              },
                            },
                          })
                        }
                      />
                    </div>
                  </div>
                  <p className="text-xs text-muted-foreground mt-2">
                    话术队列采用严格的先进先出（FIFO）顺序播放，确保播放顺序的确定性
                  </p>
                </div>
              </div>

              <Separator />

              {/* 回收站配置 */}
              <div className="space-y-4">
                <div className="flex items-center justify-between">
                  <div className="flex items-center gap-2">
                    <RefreshCw className="h-4 w-4 text-muted-foreground" />
                    <h4 className="text-sm font-medium">回收站重播</h4>
                  </div>
                  <div className="flex items-center gap-2">
                    <Switch
                      checked={playbackConfig.recycle?.enable ?? false}
                      onCheckedChange={checked =>
                        updateConfig({
                          playback: {
                            ...playbackConfig,
                            recycle: {
                              ...(playbackConfig.recycle || { probability: 20 }),
                              enable: checked,
                            },
                          },
                        })
                      }
                    />
                    <Label className="text-xs">启用</Label>
                  </div>
                </div>
                <p className="text-xs text-muted-foreground pl-6">
                  开启后，系统会按设置的概率从已播放的直播话术中随机抽取进行重播，节约AI改写token
                </p>
                {playbackConfig.recycle?.enable && (
                  <div className="space-y-3 pl-6">
                    <div className="space-y-2">
                      <Label htmlFor="recycleProbability">
                        重播概率: {playbackConfig.recycle.probability ?? 20}%
                      </Label>
                      <div className="flex items-center gap-3">
                        <Input
                          id="recycleProbability"
                          type="range"
                          min={0}
                          max={100}
                          step={5}
                          value={playbackConfig.recycle.probability ?? 20}
                          onChange={e =>
                            updateConfig({
                              playback: {
                                ...playbackConfig,
                                recycle: {
                                  ...playbackConfig.recycle!,
                                  probability: Number(e.target.value),
                                },
                              },
                            })
                          }
                          className="flex-1"
                        />
                        <span className="text-sm text-muted-foreground min-w-[3rem] text-right">
                          {playbackConfig.recycle.probability ?? 20}%
                        </span>
                      </div>
                      <p className="text-xs text-muted-foreground">
                        例如设置20%，则播放10次话术中，约有2次会重播之前播放过的话术
                      </p>
                    </div>
                  </div>
                )}
              </div>

              <Separator />

              {/* 音色切换配置 */}
              <div className="space-y-4">
                <div className="flex items-center justify-between">
                  <div className="flex items-center gap-2">
                    <RefreshCw className="h-4 w-4 text-muted-foreground" />
                    <h4 className="text-sm font-medium">音色切换</h4>
                  </div>
                  <div className="flex items-center gap-2">
                    <Switch
                      checked={config.voice.voiceRotation?.enable ?? false}
                      onCheckedChange={checked =>
                        updateConfig({
                          voice: {
                            ...config.voice,
                            voiceRotation: {
                              ...(config.voice.voiceRotation || { interval: [5, 15], voiceIds: [] }),
                              enable: checked,
                            },
                          },
                        })
                      }
                    />
                    <Label className="text-xs">启用</Label>
                  </div>
                </div>
                {config.voice.voiceRotation?.enable && (
                  <div className="space-y-3 pl-6">
                    <div className="space-y-2">
                      <Label>切换间隔范围 (分钟)</Label>
                      <div className="grid grid-cols-2 gap-3">
                        <div className="space-y-2">
                          <Label htmlFor="rotationIntervalMin">最小间隔</Label>
                          <Input
                            id="rotationIntervalMin"
                            type="number"
                            min={1}
                            max={120}
                            value={
                              Array.isArray(config.voice.voiceRotation?.interval)
                                ? config.voice.voiceRotation.interval[0]
                                : 5
                            }
                            onChange={e =>
                              updateConfig({
                                voice: {
                                  ...config.voice,
                                  voiceRotation: {
                                    ...config.voice.voiceRotation!,
                                    interval: [
                                      Number(e.target.value),
                                      Array.isArray(config.voice.voiceRotation?.interval)
                                        ? config.voice.voiceRotation.interval[1]
                                        : 15,
                                    ],
                                  },
                                },
                              })
                            }
                          />
                        </div>
                        <div className="space-y-2">
                          <Label htmlFor="rotationIntervalMax">最大间隔</Label>
                          <Input
                            id="rotationIntervalMax"
                            type="number"
                            min={1}
                            max={120}
                            value={
                              Array.isArray(config.voice.voiceRotation?.interval)
                                ? config.voice.voiceRotation.interval[1]
                                : 15
                            }
                            onChange={e =>
                              updateConfig({
                                voice: {
                                  ...config.voice,
                                  voiceRotation: {
                                    ...config.voice.voiceRotation!,
                                    interval: [
                                      Array.isArray(config.voice.voiceRotation?.interval)
                                        ? config.voice.voiceRotation.interval[0]
                                        : 5,
                                      Number(e.target.value),
                                    ],
                                  },
                                },
                              })
                            }
                          />
                        </div>
                      </div>
                      <p className="text-xs text-muted-foreground">
                        在指定时间范围内随机切换音色，模拟换人更自然
                      </p>
                    </div>
                    <div className="space-y-2">
                      <Label>选择要轮换的音色</Label>
                      <div className="space-y-2 max-h-48 overflow-y-auto border rounded-md p-3">
                        {/* 预设音色 */}
                        {(() => {
                          const presetVoices = getPresetVoicesByProvider(config.provider)
                          return presetVoices.length > 0 && (
                            <>
                              <div className="text-xs font-semibold text-muted-foreground mb-2">
                                预设音色
                              </div>
                              {presetVoices.map(voice => {
                                const isChecked = config.voice.voiceRotation?.voiceIds.includes(voice.id) ?? false
                                return (
                                  <div key={voice.id} className="flex items-center space-x-2">
                                    <Checkbox
                                      id={`voice-${voice.id}`}
                                      checked={isChecked}
                                      onCheckedChange={checked => {
                                        const currentIds = config.voice.voiceRotation?.voiceIds ?? []
                                        const newIds = checked
                                          ? [...currentIds, voice.id]
                                          : currentIds.filter(id => id !== voice.id)
                                        updateConfig({
                                          voice: {
                                            ...config.voice,
                                            voiceRotation: {
                                              ...config.voice.voiceRotation!,
                                              voiceIds: newIds,
                                            },
                                          },
                                        })
                                      }}
                                    />
                                    <Label
                                      htmlFor={`voice-${voice.id}`}
                                      className="text-sm font-normal cursor-pointer"
                                    >
                                      {voice.name}
                                    </Label>
                                  </div>
                                )
                              })}
                            </>
                          )
                        })()}
                        {/* 自定义音色 */}
                        {(config.voice.customVoices || []).length > 0 && (
                          <>
                            <div className="text-xs font-semibold text-muted-foreground mb-2 mt-3 pt-3 border-t">
                              自定义音色
                            </div>
                            {(config.voice.customVoices || []).map(voice => {
                              const isChecked = config.voice.voiceRotation?.voiceIds.includes(voice.id) ?? false
                              return (
                                <div key={voice.id} className="flex items-center space-x-2">
                                  <Checkbox
                                    id={`voice-${voice.id}`}
                                    checked={isChecked}
                                    onCheckedChange={checked => {
                                      const currentIds = config.voice.voiceRotation?.voiceIds ?? []
                                      const newIds = checked
                                        ? [...currentIds, voice.id]
                                        : currentIds.filter(id => id !== voice.id)
                                      updateConfig({
                                        voice: {
                                          ...config.voice,
                                          voiceRotation: {
                                            ...config.voice.voiceRotation!,
                                            voiceIds: newIds,
                                          },
                                        },
                                      })
                                    }}
                                  />
                                  <Label
                                    htmlFor={`voice-${voice.id}`}
                                    className="text-sm font-normal cursor-pointer"
                                  >
                                    {voice.name}
                                  </Label>
                                </div>
                              )
                            })}
                          </>
                        )}
                      </div>
                      <p className="text-xs text-muted-foreground">
                        选择多个音色进行轮换，系统会自动切换（已选择 {(() => {
                          // 只统计当前厂商的有效音色数量
                          const voiceIds = config.voice.voiceRotation?.voiceIds ?? []
                          const presetVoices = getPresetVoicesByProvider(config.provider)
                          const customVoices = config.voice.customVoices || []
                          const allValidVoiceIds = [...presetVoices, ...customVoices].map(v => v.id)
                          return voiceIds.filter(id => allValidVoiceIds.includes(id)).length
                        })()} 个）
                      </p>
                    </div>
                  </div>
                )}
              </div>

              <Separator />

              {/* 随机参数配置 */}
              <div className="space-y-4">
                <div className="flex items-center justify-between">
                  <div className="flex items-center gap-2">
                    <Shuffle className="h-4 w-4 text-muted-foreground" />
                    <h4 className="text-sm font-medium">随机化参数</h4>
                  </div>
                  <div className="flex items-center gap-2">
                    <Switch
                      checked={playbackConfig.randomization.enable}
                      onCheckedChange={checked =>
                        updateConfig({
                          playback: {
                            ...playbackConfig,
                            randomization: {
                              ...playbackConfig.randomization,
                              enable: checked,
                            },
                          },
                        })
                      }
                    />
                    <Label className="text-xs">启用</Label>
                  </div>
                </div>
                {playbackConfig.randomization.enable && (
                  <div className="space-y-4 pl-6">
                    <div className="space-y-2">
                      <Label>语速范围</Label>
                      <div className="flex items-center gap-3">
                        <Input
                          type="number"
                          min={0.5}
                          max={2.0}
                          step={0.1}
                          value={playbackConfig.randomization.speedRange[0]}
                          onChange={e =>
                            updateConfig({
                              playback: {
                                ...playbackConfig,
                                randomization: {
                                  ...playbackConfig.randomization,
                                  speedRange: [
                                    Number(e.target.value),
                                    playbackConfig.randomization.speedRange[1],
                                  ],
                                },
                              },
                            })
                          }
                          className="w-24"
                        />
                        <span className="text-sm text-muted-foreground">至</span>
                        <Input
                          type="number"
                          min={0.5}
                          max={2.0}
                          step={0.1}
                          value={playbackConfig.randomization.speedRange[1]}
                          onChange={e =>
                            updateConfig({
                              playback: {
                                ...playbackConfig,
                                randomization: {
                                  ...playbackConfig.randomization,
                                  speedRange: [
                                    playbackConfig.randomization.speedRange[0],
                                    Number(e.target.value),
                                  ],
                                },
                              },
                            })
                          }
                          className="w-24"
                        />
                      </div>
                    </div>

                    <div className="space-y-2">
                      <Label>音量范围</Label>
                      <div className="flex items-center gap-3">
                        <Input
                          type="number"
                          min={0}
                          max={100}
                          value={playbackConfig.randomization.volumeRange[0]}
                          onChange={e =>
                            updateConfig({
                              playback: {
                                ...playbackConfig,
                                randomization: {
                                  ...playbackConfig.randomization,
                                  volumeRange: [
                                    Number(e.target.value),
                                    playbackConfig.randomization.volumeRange[1],
                                  ],
                                },
                              },
                            })
                          }
                          className="w-24"
                        />
                        <span className="text-sm text-muted-foreground">至</span>
                        <Input
                          type="number"
                          min={0}
                          max={100}
                          value={playbackConfig.randomization.volumeRange[1]}
                          onChange={e =>
                            updateConfig({
                              playback: {
                                ...playbackConfig,
                                randomization: {
                                  ...playbackConfig.randomization,
                                  volumeRange: [
                                    playbackConfig.randomization.volumeRange[0],
                                    Number(e.target.value),
                                  ],
                                },
                              },
                            })
                          }
                          className="w-24"
                        />
                      </div>
                    </div>

                    <div className="space-y-2">
                      <Label>音调范围</Label>
                      <div className="flex items-center gap-3">
                        <Input
                          type="number"
                          min={-500}
                          max={500}
                          step={1}
                          value={playbackConfig.randomization.pitchRange[0]}
                          onChange={e =>
                            updateConfig({
                              playback: {
                                ...playbackConfig,
                                randomization: {
                                  ...playbackConfig.randomization,
                                  pitchRange: [
                                    Number(e.target.value),
                                    playbackConfig.randomization.pitchRange[1],
                                  ],
                                },
                              },
                            })
                          }
                          className="w-24"
                        />
                        <span className="text-sm text-muted-foreground">至</span>
                        <Input
                          type="number"
                          min={-500}
                          max={500}
                          step={10}
                          value={playbackConfig.randomization.pitchRange[1]}
                          onChange={e =>
                            updateConfig({
                              playback: {
                                ...playbackConfig,
                                randomization: {
                                  ...playbackConfig.randomization,
                                  pitchRange: [
                                    playbackConfig.randomization.pitchRange[0],
                                    Number(e.target.value),
                                  ],
                                },
                              },
                            })
                          }
                          className="w-24"
                        />
                      </div>
                    </div>
                    <p className="text-xs text-muted-foreground">
                      每次播报时在指定范围内随机选择参数值，模拟真实说话
                    </p>
                  </div>
                )}
              </div>

              <Separator />

              {/* 报时播报 */}
              <div className="space-y-4">
                <div className="flex items-center justify-between">
                  <div className="flex items-center gap-2">
                    <Clock className="h-4 w-4 text-muted-foreground" />
                    <h4 className="text-sm font-medium">报时播报</h4>
                  </div>
                  <div className="flex items-center gap-2">
                    <Switch
                      checked={playbackConfig.timeAnnouncement?.enable ?? false}
                      onCheckedChange={checked =>
                        updateConfig({
                          playback: {
                            ...playbackConfig,
                            timeAnnouncement: {
                              ...(playbackConfig.timeAnnouncement || { interval: { min: 5, max: 15 }, templates: [], mode: 'random' }),
                              enable: checked,
                            },
                          },
                        })
                      }
                    />
                    <Label className="text-xs">启用</Label>
                  </div>
                </div>
                {playbackConfig.timeAnnouncement?.enable && (
                  <div className="space-y-3 pl-6">
                    <div className="grid grid-cols-2 gap-3">
                      <div className="space-y-2">
                        <Label htmlFor="timeAnnouncementMin">最小间隔 (分钟)</Label>
                        <Input
                          id="timeAnnouncementMin"
                          type="number"
                          min={1}
                          max={120}
                          value={playbackConfig.timeAnnouncement?.interval?.min ?? 5}
                          onChange={e =>
                            updateConfig({
                              playback: {
                                ...playbackConfig,
                                timeAnnouncement: {
                                  ...playbackConfig.timeAnnouncement!,
                                  interval: {
                                    min: Number(e.target.value),
                                    max: playbackConfig.timeAnnouncement?.interval?.max ?? 15,
                                  },
                                },
                              },
                            })
                          }
                        />
                      </div>
                      <div className="space-y-2">
                        <Label htmlFor="timeAnnouncementMax">最大间隔 (分钟)</Label>
                        <Input
                          id="timeAnnouncementMax"
                          type="number"
                          min={1}
                          max={120}
                          value={playbackConfig.timeAnnouncement?.interval?.max ?? 15}
                          onChange={e =>
                            updateConfig({
                              playback: {
                                ...playbackConfig,
                                timeAnnouncement: {
                                  ...playbackConfig.timeAnnouncement!,
                                  interval: {
                                    min: playbackConfig.timeAnnouncement?.interval?.min ?? 5,
                                    max: Number(e.target.value),
                                  },
                                },
                              },
                            })
                          }
                        />
                      </div>
                    </div>
                    <div className="space-y-2">
                      <Label htmlFor="timeAnnouncementTemplates">播报模板 (每行一个，使用{'{时间}'}作为占位符)</Label>
                      <Textarea
                        id="timeAnnouncementTemplates"
                        placeholder="例如:&#10;现在是{时间}&#10;当前时间{时间}&#10;看看现在几点了，{时间}"
                        value={(playbackConfig.timeAnnouncement?.templates || []).join('\n')}
                        onChange={e =>
                          updateConfig({
                            playback: {
                              ...playbackConfig,
                              timeAnnouncement: {
                                ...playbackConfig.timeAnnouncement!,
                                templates: e.target.value
                                  .split('\n')
                                  .map(t => t.trim())
                                  .filter(Boolean),
                              },
                            },
                          })
                        }
                        className="min-h-[160px] resize-y"
                      />
                      <p className="text-xs text-muted-foreground">
                        系统会在指定时间间隔内随机播报时间，使用{'{时间}'}作为时间占位符
                      </p>
                    </div>
                  </div>
                )}
              </div>

              <Separator />

              {/* 欢迎用户播报 */}
              <div className="space-y-4">
                <div className="flex items-center justify-between">
                  <div className="flex items-center gap-2">
                    <MessageSquareText className="h-4 w-4 text-muted-foreground" />
                    <h4 className="text-sm font-medium">用户互动播报</h4>
                  </div>
                  <div className="flex items-center gap-2">
                    <Switch
                      checked={playbackConfig.userInteraction?.enable ?? false}
                      onCheckedChange={checked =>
                        updateConfig({
                          playback: {
                            ...playbackConfig,
                            userInteraction: {
                              ...(playbackConfig.userInteraction || { 
                                interval: { min: 30, max: 60 },
                                deduplication: { enable: true, duration: 60 },
                                templates: {
                                  room_enter: ['欢迎{用户}来到直播间'],
                                  room_like: ['感谢{用户}的点赞'],
                                  room_follow: ['感谢{用户}的关注'],
                                  subscribe_merchant_brand_vip: ['欢迎{用户}加入品牌会员'],
                                  live_order: ['感谢{用户}购买{商品}'],
                                  ecom_fansclub_participate: ['欢迎{用户}加入粉丝团'],
                                }, 
                                mode: 'random',
                                playMode: 'next'
                              }),
                              enable: checked,
                            },
                          },
                        })
                      }
                    />
                    <Label className="text-xs">启用</Label>
                  </div>
                </div>
                {playbackConfig.userInteraction?.enable && (
                  <div className="space-y-4 pl-6">
                    {/* ✅ 新增：播放模式配置 */}
                    <div className="space-y-2 border rounded-md p-3 bg-blue-50 dark:bg-blue-950/20">
                      <Label htmlFor="userInteractionPlayMode" className="text-sm font-medium">播放模式</Label>
                      <Select
                        value={playbackConfig.userInteraction?.playMode || 'next'}
                        onValueChange={(value: 'immediate' | 'next') =>
                          updateConfig({
                            playback: {
                              ...config.playback,
                              userInteraction: {
                                ...(config.playback?.userInteraction || playbackConfig.userInteraction)!,
                                playMode: value,
                              },
                            },
                          })
                        }
                      >
                        <SelectTrigger id="userInteractionPlayMode">
                          <SelectValue />
                        </SelectTrigger>
                        <SelectContent>
                          <SelectItem value="immediate">立即播放（打断当前）</SelectItem>
                          <SelectItem value="next">等待播放完成</SelectItem>
                        </SelectContent>
                      </Select>
                      <p className="text-xs text-muted-foreground">
                        选择用户互动播报的播放方式：立即打断当前播放，还是等待当前播放完成后再播放
                      </p>
                    </div>
                    {/* 播报间隔 */}
                    <div className="grid grid-cols-2 gap-3">
                      <div className="space-y-2">
                        <Label htmlFor="userInteractionMin">最小间隔 (秒)</Label>
                        <Input
                          id="userInteractionMin"
                          type="number"
                          min={5}
                          max={3600}
                          value={playbackConfig.userInteraction?.interval?.min ?? 30}
                          onChange={e =>
                            updateConfig({
                              playback: {
                                ...playbackConfig,
                                userInteraction: {
                                  ...playbackConfig.userInteraction!,
                                  interval: {
                                    min: Number(e.target.value),
                                    max: playbackConfig.userInteraction?.interval?.max ?? 60,
                                  },
                                },
                              },
                            })
                          }
                        />
                      </div>
                      <div className="space-y-2">
                        <Label htmlFor="userInteractionMax">最大间隔 (秒)</Label>
                        <Input
                          id="userInteractionMax"
                          type="number"
                          min={5}
                          max={3600}
                          value={playbackConfig.userInteraction?.interval?.max ?? 60}
                          onChange={e =>
                            updateConfig({
                              playback: {
                                ...playbackConfig,
                                userInteraction: {
                                  ...playbackConfig.userInteraction!,
                                  interval: {
                                    min: playbackConfig.userInteraction?.interval?.min ?? 30,
                                    max: Number(e.target.value),
                                  },
                                },
                              },
                            })
                          }
                        />
                      </div>
                    </div>
                    
                    {/* 防重复播报配置 */}
                    <div className="space-y-3 border-t pt-3">
                      <div className="flex items-center justify-between">
                        <div className="space-y-1">
                          <Label className="text-sm font-medium">防重复播报</Label>
                          <p className="text-xs text-muted-foreground">
                            防止在短时间内重复播报同一用户的互动
                          </p>
                        </div>
                        <Switch
                          checked={playbackConfig.userInteraction?.deduplication?.enable ?? false}
                          onCheckedChange={checked =>
                            updateConfig({
                              playback: {
                                ...playbackConfig,
                                userInteraction: {
                                  ...playbackConfig.userInteraction!,
                                  deduplication: {
                                    ...(playbackConfig.userInteraction?.deduplication || { duration: 60 }),
                                    enable: checked,
                                  },
                                },
                              },
                            })
                          }
                        />
                      </div>
                      {playbackConfig.userInteraction?.deduplication?.enable && (
                        <div className="space-y-2 pl-6">
                          <Label htmlFor="deduplicationDuration">防重复时间窗口 (秒)</Label>
                          <Input
                            id="deduplicationDuration"
                            type="number"
                            min={10}
                            max={600}
                            value={playbackConfig.userInteraction?.deduplication?.duration ?? 60}
                            onChange={e =>
                              updateConfig({
                                playback: {
                                  ...playbackConfig,
                                  userInteraction: {
                                    ...playbackConfig.userInteraction!,
                                    deduplication: {
                                      ...playbackConfig.userInteraction!.deduplication!,
                                      duration: Number(e.target.value),
                                    },
                                  },
                                },
                              })
                            }
                          />
                          <p className="text-xs text-muted-foreground">
                            在此时间窗口内，同一用户的互动不会被重复播报（例如：一个用户连续点赞）
                          </p>
                        </div>
                      )}
                    </div>
                    
                    {/* 不同互动类型的模板配置 */}
                    <div className="space-y-3">
                      <Label className="text-sm font-medium">互动类型模板</Label>
                      <p className="text-xs text-muted-foreground mb-2">
                        为不同的用户互动行为配置专属播报话术。使用 {'{用户}'} 作为用户名占位符，{'{商品}'} 作为商品名占位符。
                      </p>
                      
                      <div className="space-y-3">
                        {/* 进入直播间 */}
                        <div className="space-y-2">
                          <Label htmlFor="template_room_enter" className="text-xs">进入直播间</Label>
                          <Textarea
                            id="template_room_enter"
                            placeholder="例如:&#10;欢迎{用户}来到直播间&#10;欢迎{用户}的到来"
                            value={(playbackConfig.userInteraction?.templates?.room_enter || []).join('\n')}
                            onChange={e =>
                              updateConfig({
                                playback: {
                                  ...playbackConfig,
                                  userInteraction: {
                                    ...playbackConfig.userInteraction!,
                                    templates: {
                                      ...playbackConfig.userInteraction!.templates,
                                      room_enter: e.target.value.split('\n'),
                                    },
                                  },
                                },
                              })
                            }
                            className="min-h-[120px] resize-y text-xs"
                          />
                        </div>
                        
                        {/* 点赞直播 */}
                        <div className="space-y-2">
                          <Label htmlFor="template_room_like" className="text-xs">点赞直播</Label>
                          <Textarea
                            id="template_room_like"
                            placeholder="例如:&#10;感谢{用户}的点赞&#10;谢谢{用户}点赞支持"
                            value={(playbackConfig.userInteraction?.templates?.room_like || []).join('\n')}
                            onChange={e =>
                              updateConfig({
                                playback: {
                                  ...playbackConfig,
                                  userInteraction: {
                                    ...playbackConfig.userInteraction!,
                                    templates: {
                                      ...playbackConfig.userInteraction!.templates,
                                      room_like: e.target.value.split('\n'),
                                    },
                                  },
                                },
                              })
                            }
                            className="min-h-[120px] resize-y text-xs"
                          />
                        </div>
                        
                        {/* 关注直播间 */}
                        <div className="space-y-2">
                          <Label htmlFor="template_room_follow" className="text-xs">关注直播间</Label>
                          <Textarea
                            id="template_room_follow"
                            placeholder="例如:&#10;感谢{用户}的关注&#10;欢迎{用户}关注直播间"
                            value={(playbackConfig.userInteraction?.templates?.room_follow || []).join('\n')}
                            onChange={e =>
                              updateConfig({
                                playback: {
                                  ...playbackConfig,
                                  userInteraction: {
                                    ...playbackConfig.userInteraction!,
                                    templates: {
                                      ...playbackConfig.userInteraction!.templates,
                                      room_follow: e.target.value.split('\n'),
                                    },
                                  },
                                },
                              })
                            }
                            className="min-h-[120px] resize-y text-xs"
                          />
                        </div>
                        
                        {/* 加入品牌会员 */}
                        <div className="space-y-2">
                          <Label htmlFor="template_brand_vip" className="text-xs">加入品牌会员</Label>
                          <Textarea
                            id="template_brand_vip"
                            placeholder="例如:&#10;欢迎{用户}加入品牌会员&#10;感谢{用户}成为品牌会员"
                            value={(playbackConfig.userInteraction?.templates?.subscribe_merchant_brand_vip || []).join('\n')}
                            onChange={e =>
                              updateConfig({
                                playback: {
                                  ...playbackConfig,
                                  userInteraction: {
                                    ...playbackConfig.userInteraction!,
                                    templates: {
                                      ...playbackConfig.userInteraction!.templates,
                                      subscribe_merchant_brand_vip: e.target.value.split('\n'),
                                    },
                                  },
                                },
                              })
                            }
                            className="min-h-[120px] resize-y text-xs"
                          />
                        </div>
                        
                        {/* 购买商品 */}
                        <div className="space-y-2">
                          <Label htmlFor="template_live_order" className="text-xs">购买商品</Label>
                          <Textarea
                            id="template_live_order"
                            placeholder="例如:&#10;感谢{用户}购买{商品}&#10;谢谢{用户}的订单"
                            value={(playbackConfig.userInteraction?.templates?.live_order || []).join('\n')}
                            onChange={e =>
                              updateConfig({
                                playback: {
                                  ...playbackConfig,
                                  userInteraction: {
                                    ...playbackConfig.userInteraction!,
                                    templates: {
                                      ...playbackConfig.userInteraction!.templates,
                                      live_order: e.target.value.split('\n'),
                                    },
                                  },
                                },
                              })
                            }
                            className="min-h-[120px] resize-y text-xs"
                          />
                        </div>
                        
                        {/* 加入粉丝团 */}
                        <div className="space-y-2">
                          <Label htmlFor="template_fansclub" className="text-xs">加入粉丝团</Label>
                          <Textarea
                            id="template_fansclub"
                            placeholder="例如:&#10;欢迎{用户}加入粉丝团&#10;感谢{用户}加入粉丝团"
                            value={(playbackConfig.userInteraction?.templates?.ecom_fansclub_participate || []).join('\n')}
                            onChange={e =>
                              updateConfig({
                                playback: {
                                  ...playbackConfig,
                                  userInteraction: {
                                    ...playbackConfig.userInteraction!,
                                    templates: {
                                      ...playbackConfig.userInteraction!.templates,
                                      ecom_fansclub_participate: e.target.value.split('\n'),
                                    },
                                  },
                                },
                              })
                            }
                            className="min-h-[120px] resize-y text-xs"
                          />
                        </div>
                      </div>
                    </div>
                  </div>
                )}
              </div>

              <Separator />

              {/* 停顿配置 */}
              <div className="space-y-4">
                <div className="flex items-center justify-between">
                  <div className="flex items-center gap-2">
                    <PauseIcon className="h-4 w-4 text-muted-foreground" />
                    <h4 className="text-sm font-medium">停顿设置</h4>
                  </div>
                  <div className="flex items-center gap-2">
                    <Switch
                      checked={playbackConfig.pause.enable}
                      onCheckedChange={checked =>
                        updateConfig({
                          playback: {
                            ...playbackConfig,
                            pause: {
                              ...playbackConfig.pause,
                              enable: checked,
                            },
                          },
                        })
                      }
                    />
                    <Label className="text-xs">启用</Label>
                  </div>
                </div>
                {playbackConfig.pause.enable && (
                  <div className="space-y-3 pl-6">
                    <div className="space-y-2">
                      <Label>停顿时长范围 (毫秒)</Label>
                      <div className="flex items-center gap-3">
                        <Input
                          type="number"
                          min={0}
                          max={5000}
                          step={100}
                          value={playbackConfig.pause.duration[0]}
                          onChange={e =>
                            updateConfig({
                              playback: {
                                ...playbackConfig,
                                pause: {
                                  ...playbackConfig.pause,
                                  duration: [
                                    Number(e.target.value),
                                    playbackConfig.pause.duration[1],
                                  ],
                                },
                              },
                            })
                          }
                          className="w-28"
                        />
                        <span className="text-sm text-muted-foreground">至</span>
                        <Input
                          type="number"
                          min={0}
                          max={5000}
                          step={100}
                          value={playbackConfig.pause.duration[1]}
                          onChange={e =>
                            updateConfig({
                              playback: {
                                ...playbackConfig,
                                pause: {
                                  ...playbackConfig.pause,
                                  duration: [
                                    playbackConfig.pause.duration[0],
                                    Number(e.target.value),
                                  ],
                                },
                              },
                            })
                          }
                          className="w-28"
                        />
                      </div>
                      <p className="text-xs text-muted-foreground">
                        在播报间添加随机停顿，更自然
                      </p>
                    </div>
                  </div>
                )}
              </div>
            </TabsContent>
          </ScrollArea>
        </Tabs>
      </DialogContent>
    </Dialog>
  )
}

